/* eslint-disable */
<template>
  <div class="productMsg">
    <div class="proMsgSec">
      <!-- 商品管理弹出框 -->
      <el-dialog
        :title="dialable"
        :visible.sync="dialogFormVisible"
        v-if="dialogFormVisible"
        width="33%"
      >
        <el-form :model="form" class="diaform" :rules="rules" ref="form">
          <el-form-item label="商品名称" :label-width="formLabelWidth" prop="productName">
            <el-input v-model="form.productName" autocomplete="off" style="width:51%"></el-input>
          </el-form-item>
          <!-- <el-form-item label="自定义商品id" :label-width="formLabelWidth">
            <el-input v-model="form.customSkuId" autocomplete="off" style="width:51%"></el-input>
          </el-form-item>
          <el-form-item label="销售价格(元)" :label-width="formLabelWidth">
            <el-input v-model="form.salePrice" autocomplete="off" @blur="xiaonum" style="width:51%"></el-input>
            //<div class="tip" :class="{hidden: ishidden}">小数点后最多保存2位</div>
            <el-alert
              title="小数点后最多保存2位"
              type="error"
              show-icon
              :class="{hidden: ishidden}"
              style="padding:0px 16px;width:51%"
            ></el-alert>
          </el-form-item> -->
          <!-- <el-form-item label="库存数量" :label-width="formLabelWidth">
            <el-input v-model="form.leftNum" autocomplete="off" style="width:51%"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="商品状态" :label-width="formLabelWidth">
            <el-select v-model="form.status" placeholder="请选择商品状态">
              <el-option label="上架" value="1"></el-option>
              <el-option label="下架" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品图片"
            :label-width="formLabelWidth"
            prop="productImg"
            ref="productImg"
          >
            <ImgUpload @listenEvent="imgfn" :queryImg="form.productImg" v-model="form.productImg"></ImgUpload>
          </el-form-item>
          <el-form-item label="商品分类" :label-width="formLabelWidth" prop="jilianvalue">
            <el-cascader
              v-model="form.jilianvalue"
              :options="options"
              @change="handlejilianChange"
              autocomplete="off"
              style="width:51%"
            ></el-cascader>
          </el-form-item>-->
          <el-form-item label="条码" :label-width="formLabelWidth" prop="upc">
            <el-input v-model="form.upc" autocomplete="off" style="width:51%"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false;quxiao()">取 消</el-button>
          <el-button type="success" @click="submitEdit();" :class="{ showactive: isActive }">编 辑</el-button>
          <el-button
            type="primary"
            @click="submitForm('form')"
            :class="{ showactive: !isActive }"
          >添 加</el-button>
        </div>
      </el-dialog>
      <!-- 查询 -->
      <el-row>
        <el-col :span="20">
          <div>
            查询:
            <el-input
              v-model="searchName"
              style="width: 30%;margin-right:10px"
              placeholder="可输入商户名称、商品名称、自定义产品id"
              clearable
            ></el-input>
            <el-date-picker
              v-model="value1"
              type="date"
              style="margin-right:40px"
              @change="onPick"
            ></el-date-picker>
            <el-button type="primary" size="small" @click="seachbtn()" style="font-size:14px">查 询</el-button>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button
            size="small"
            class="button"
            round
            @click="dialogFormVisible = true;isActive=true;addbtn()"
            style="font-size:14px"
          >添 加</el-button>
        </el-col>
      </el-row>
    </div>

    <div class="proMsgTab">
      <!-- 商品列表 -->

      <el-table :data="tableData" style="width: 100%">
        <!-- <el-table-column label="条码" prop="upc"></el-table-column> -->
        <el-table-column label="自定义商品id" prop="customSkuId"></el-table-column>
        <el-table-column label="商品名称" prop="productName"></el-table-column>
        <!-- <el-table-column label="商品图片" prop="productImg">
          <template slot-scope="scope">
            <img
              :src="scope.row.productImg"
              alt
              style="width:50px;height:36px"
              @click="getimg(scope.row.productImg)"
            />
          </template>
        </el-table-column> -->
        <el-table-column label="成本均价(单位：元)" prop="salePrice">
          <template slot-scope="scope">
            {{scope.row.avgCostPrice/100}}
            <!-- <span>元</span> -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="库存" prop="leftNum" width="80"></el-table-column> -->

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.$index, scope.row);dialogFormVisible = true"
            >
              <span style="color:#3dc2c2;font-size:14px" @click="isActive=false">编辑</span>
            </el-button>
            <el-button size="mini" type="text" @click="handledel(scope.$index, scope.row);open()">
              <span style="color:#f7674a;font-size:14px">删除</span>
            </el-button>
            <!-- <el-button
              size="mini"
              type="text"
              @click="handleOn(scope.$index, scope.row)"
              :class="{ hidden: scope.row.status==1 }"
            >
              <span style="color:#409eff;font-size:14px">上架</span>
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleOff(scope.$index, scope.row)"
              :class="{ hidden: scope.row.status==0 }"
            >
              <span style="color:#71dc80;font-size:14px">下架</span>
            </el-button> -->
            <el-button @click="handleClick(scope.row)" type="text" size="small">
              <span style="font-size:14px">商户列表</span>
            </el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <img src="../../assets/blank_tip_page/blank_tip_page.png" alt />
        </div>
      </el-table>
      <el-pagination
        align="right"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="pageSizes"
        :page-size="perPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog
      title="商品图片"
      :visible.sync="dialogFormVisibleimg"
      v-if="dialogFormVisibleimg"
      width="33%"
      center
    >
      <div class="dialogDiv">
        <img
          :src="this.imgmax"
          alt
          style="width: 100%;
                height: auto;
                max-width: 100%;
               max-height: 100%;"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import ImgUpload from "./imgupload";
export default {
  name: "productMsg",
  components: {
    ImgUpload
  },
  data() {
    let validateFileUrl = (rule, value, callback) => {
      // console.log(this.form.productImg)
      if (this.form.productImg == null) {
        //  console.log(value)
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    let validateFileSalePrice = (rule, value, callback) => {
      if (value == null) {
        callback(new Error("请输入销售价格(元)"));
      } else if (!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(value)) {
        callback(new Error("价格是整数或2位小数"));
      } else {
        callback();
      }
    };
    let validateFileLeftNum = (rule, value, callback) => {
      if (value == null) {
        callback(new Error("请输入库存"));
      } else if (!/(^[1-9]\d*$)/.test(value)) {
        callback(new Error("库存必须是整数"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      pageSizes: [1, 5, 10, 20],
      total: 20, // 总条数
      perPage: 10,
      page: 1,
      searchName: "",
      value1: new Date(),
      form: {
        productName: "",
        customSkuId: "",
        salePrice: "",
        leftNum: "",
        status: "",
        productImg: "",
        elmMarketCategoryId: "",
        elmMarketCategorySecondId: "",
        elmMarketCategoryThirdId: "",
        upc: "",
        id: "",
        jilianvalue: []
      },
      dialogFormVisible: false,
      dialable: "",
      formLabelWidth: "120px",
      id: "",
      isActive: false,
      ishidden: true,
      ishidden2: true,
      dialogFormVisibleimg: false,
      imgmax: "",
      loading: true,
      rules: {
        productName: [
          { required: true, message: "请输入商品名称", trigger: "change" }
        ],
        customSkuId: [
          { required: true, message: "请输入自定义商品id", trigger: "blur" }
        ],
        salePrice: [
          {
            required: true,
            validator: validateFileSalePrice,
            trigger: ["change"]
          }
        ],
        leftNum: [
          {
            required: true,
            validator: validateFileLeftNum,
            trigger: ["change"]
          }
        ],
        status: [
          { required: true, message: "请选择商品状态", trigger: "change" }
        ],
        // productImg: [
        //   {type: 'string', required: true, message: '请上传商品图片' , trigger: 'change'}
        // ],
        productImg: [
          { required: true, validator: validateFileUrl, trigger: ["change"] }
        ],
        // jilianvalue: [
        //   {type: 'array', required: true, message: '请选择商品分类', trigger: 'change' }
        // ],
        upc: [{ required: true, message: "请输入条码", trigger: "change" }]
      },
      options: [
        {
          value: "0",
          label: "一级1",
          children: [
            {
              value: "0",
              label: "1二级1",
              children: [
                {
                  value: "0",
                  label: "11三级1"
                },
                {
                  value: "32",
                  label: "11三级2"
                }
              ]
            },
            {
              value: "22",
              label: "1二级2",
              children: [
                {
                  value: "311",
                  label: "12三级1"
                },
                {
                  value: "322",
                  label: "12三级2"
                }
              ]
            }
          ]
        },
        {
          value: "1",
          label: "一级2",
          children: [
            {
              value: "12",
              label: "2二级1",
              children: [
                {
                  value: "131",
                  label: "21三级1"
                },
                {
                  value: "132",
                  label: "21三级2"
                }
              ]
            },
            {
              value: "122",
              label: "2二级2",
              children: [
                {
                  value: "231",
                  label: "22三级1"
                },
                {
                  value: "232",
                  label: "22三级2"
                }
              ]
            }
          ]
        },
        {
          value: "32121",
          label: "一级3",
          children: [
            {
              value: "3211",
              label: "3二级1"
            },
            {
              value: "2121",
              label: "3二级2"
            }
          ]
        }
      ]
    };
  },
  created() {},
  mounted() {
    this.getproductMsg();
  },
  methods: {
    handleEdit(index, row) {
      // console.log(index, row);
      // this.form = row;
      this.dialable = "商品编辑";
      // console.log(this.dialable)
      this.form.id = row.id;
      this.getproductShow();

      this.form.salePrice = this.form.salePrice / 100;
    },
    quxiao() {
      this.getproductMsg();
    },
    open() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("productMsg/getproductDel", {
              id: this.id
            })
            .then(data => {
              // console.log(data);
              // console.log(this.total)
              if ((this.total - 1) % this.perPage == 0) this.page--;
              this.getproductMsg();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            })
            .catch(err => {
              // console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handledel(index, row) {
      // console.log(index, row);
      this.id = row.id;
    },

    seachbtn() {
      this.getproductMsg();
    },
    submitEdit() {
      this.$store
        .dispatch("productMsg/getproductEdit", {
          productName: this.form.productName,
          customSkuId: this.form.customSkuId,
          salePrice: (this.form.salePrice - 0) * 100,
          leftNum: this.form.leftNum,
          status: this.form.status,
          productImg: this.form.productImg,
          id: this.form.elmMarketCategoryId,
          elmMarketCategorySecondId: this.form.elmMarketCategorySecondId,
          elmMarketCategoryThirdId: this.form.elmMarketCategoryThirdId,
          upc: this.form.upc,
          id: this.form.id
        })
        .then(res => {
          // console.log(res);
          if (res) {
            this.getproductMsg();
            this.$message({
              message: "编辑成功",
              type: "success"
            });
            this.dialogFormVisible = false;
          } else if (res == undefined) {
            this.dialogFormVisible = true;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    addbtn() {
      this.dialable = "商品添加";
      this.$store.state.productMsg.productImg=""
      this.form = {};

      // this.form.productImg = "";
      // this.form.jilianvalue=[]
      // console.log(this.form)
    },
    handleAdd() {
      this.$store
        .dispatch("productMsg/getproductAdd", {
          productName: this.form.productName,
          customSkuId: this.form.customSkuId,
          salePrice: (this.form.salePrice - 0) * 100,
          leftNum: this.form.leftNum,
          status: this.form.status,
          productImg: this.form.productImg,
          // elmMarketCategoryId: this.form.jilianvalue[0]*1,
          // elmMarketCategorySecondId: this.form.jilianvalue[1]*1,
          // elmMarketCategoryThirdId: this.form.jilianvalue[2]*1,
          upc: this.form.upc
        })
        .then(res => {
          // console.log(res);
          if (res) {
            // console.log(res + "添加");
            this.getproductMsg();
            // console.log(this.jilianvalue)
            this.$message({
              message: "添加成功",
              type: "success"
            });
            this.dialogFormVisible = false;
          } else if (res == undefined) {
            this.dialogFormVisible = true;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleOn(index, row) {
      // console.log(index, row);
      this.$store
        .dispatch("productMsg/getproductOn", {
          status: 1,
          id: row.id
        })
        .then(data => {
          // console.log(data);
          this.getproductMsg();
          this.$message({
            message: "上架成功",
            type: "success"
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleOff(index, row) {
      this.$store
        .dispatch("productMsg/getproductOn", {
          status: 0,
          id: row.id
        })
        .then(data => {
          this.getproductMsg();
          this.$message({
            message: "下架成功",
            type: "success"
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.loading = false;
      this.perPage = val;
      this.page = 1;
      this.getproductMsg();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.loading = false;
      this.page = val;
      this.getproductMsg();
    },
    dateFormat(time) {
      let date = new Date(time);
      let year = date.getFullYear();

      let month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

      return year + "-" + month + "-" + day;
    },
    onPick(date){
      this.value1 = date
    },
    getproductMsg() {
      this.$store
        .dispatch("productMsg/getproductMsg", {
          searchName: this.searchName,
          targetDate: this.dateFormat(this.value1),
          perPage: this.perPage,
          page: this.page
        })
        .then(data => {
          // console.log(data);
          this.loading = false;
          this.tableData = data.items;
          this.total = data.total;
        })
        .catch(err => {
          console.log(err);
        });
      this.loading = true;
    },
    getproductShow() {
      this.$store
        .dispatch("productMsg/getproductShow", {
          id: this.form.id
        })
        .then(data => {
          // data.jilianvalue=[data.elmMarketCategoryId+"",data.elmMarketCategorySecondId+"",data.elmMarketCategoryThirdId+ ""]
          this.form = data;
          this.form.salePrice = data.salePrice / 100;
          this.form.productImg = data.productImg;
          this.form.status = data.status + "";
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleClick(row) {
      console.log(row)
      const elmMarketProductId = row.id
      const productName = row.productName
      this.$router.push({
        path: `businessList/${elmMarketProductId}`,
        query: {
          elmMarketProductId: elmMarketProductId,
          productName: productName
        }
      })
    },
    xiaonum() {
      if (this.form.salePrice.toString().split(".")[1].length > 2) {
        // alert("小数点后最多两位小数")
        this.ishidden = false;
      } else {
        this.ishidden = true;
      }
    },
  //  xiaonum2() {
  //     if (this.form.leftNum.toString().split(".")[1].length !=undefined) {

  //       this.ishidden2 = false;
  //     } else {
  //       this.ishidden2 = true;
  //     }
  //   },
    getimg(img) {
      // console.log(img)
      this.imgmax = img;
      this.dialogFormVisibleimg = true;
    },
    imgfn(param) {
      this.form.productImg = param;
      this.$refs.productImg.clearValidate();
    },
    handlejilianChange(value) {
      //   console.log(value);
      //  this.form.jilianvalue=value;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // alert('submit!');
          this.handleAdd();
        } else {
          this.$message.error("有必填项未填");
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
  text-align: center;
}
::v-deep .el-form-item {
  margin-bottom: 16px;
}
::v-deep .el-form-item__conten {
  line-height: 0px;
}
.proMsgSec,
.proMsgTab {
  background: #fff;
  padding: 5px;
  padding-left: 15px;
  margin-bottom: 20px;
  padding-top: 15px;
  padding-bottom: 15px;
}
.flex {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  // margin-top: 10px;
  margin-right: 10px;
}
.showactive,
.hidden {
  display: none;
}
.tip {
  color: red;
}
.proMsgSec ::v-deep .el-input__inner {
  height: 34px;
  line-height: 34px;
}
.dialogDiv {
  height: 430px;
  overflow: auto;
}
.button {
  background: #64d9d6;
  color: #fff;
}
</style>


